<!-- 账户列表管理 -->
<template>
    <div >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
                <a-row :gutter='48'>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="开户行">
                            <a-input v-model="channel" placeholder="请输入开户行" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="账户名称">
                            <a-input v-model="accountName" placeholder="请输入账户名称" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="账号">
                            <a-input v-model="bankAccount" placeholder="请输入账号" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='16' :sm='24'>
                        <a-form-item label="时间">
                            <a-range-picker style="width: 100%" @change="onDateChange" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="联动设置">
                            <a-select v-model="linkageType" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="item in linkageTypeList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='16' :sm='24'>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button type='primary' @click="getData">查询</a-button>
                            <a-button v-if="hasPower('createLaborAccount')" style="margin-left: 20px" type='' icon="plus" @click="add">添加账户</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  

        <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ total: total ,showSizeChanger: true,pageSize: size,}" size="small" :scroll="{ x: 1500, }">
            <div slot="accountType" slot-scope="accountType">
                <div v-for="(item,i) in accountTypeList" :key="item.id">
                    <a-tag v-if="item.id == accountType" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div>
            <div slot="linkageType" slot-scope="linkageType">
                <div v-for="(item,i) in linkageTypeList" :key="item.id">
                    <a-tag v-if="item.id == linkageType" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div>
            <div slot="companyName" slot-scope="companyName">
                <ellipsis :length="6" tooltip>{{ companyName }}</ellipsis>
            </div>
            <div slot="customerName" slot-scope="customerName">
                <ellipsis :length="6" tooltip>{{ customerName }}</ellipsis>
            </div>
            <div slot="operation" slot-scope="text,record">
                <div class="editable-row-operations">
                    <a-button type="link" @click="invest(record)">充值</a-button>
                    <a-button type="link" v-if="hasPower('accountWithdraw') && record.linkageType != 1" @click="withdraw(record)">提现</a-button>
                    <a-button type="link" @click="detail(record)">详情</a-button>
                    <a-button type="link" v-if="hasPower('updateLaborAccount')" @click="update(record)">编辑</a-button>
                </div>
            </div>
        </a-table>

        <a-modal 
            v-model="visible" 
            :title="isAdd ? '添加账户' : '编辑账户'"
            @ok="handleOk" 
            :forceRender="true"
            @cancel="visible = false">
            <div>
                <a-form-model :model="account" ref="ruleForm" :rules="rules" :label-col="{ span: 7 }" :wrapper-col="{ span: 17 }">
                    <a-form-model-item label="开户行" prop="channel">
                        <a-input :disabled="!isAdd" v-model="account.channel" placeholder="请输入开户行信息" />
                    </a-form-model-item>
                    <a-form-model-item label="账户名称" prop="accountName">
                        <a-input :disabled="!isAdd" v-model="account.accountName" placeholder="请输入账户名称" />
                    </a-form-model-item>
                    <a-form-model-item label="账户简称">
                        <a-input v-model="account.accountShortName" placeholder="请输入账户简称" />
                    </a-form-model-item>
                    <a-form-model-item label="银行账号" prop="bankAccount">
                        <a-input :disabled="!isAdd" v-model="account.bankAccount" placeholder="请输入银行账号" />
                    </a-form-model-item>
                    <a-form-model-item label="账户类型" prop="accountType">
                        <a-select v-model="account.accountType">
                            <a-select-option v-for="type in accountTypeList" :key="type.id" :value="type.id">{{type.name}}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="联动设置" prop="linkageType" help="提示：修改“联动设置”，将会清空账户已设置的交易密码和提现账户，请谨慎操作">
                        <a-radio-group v-model="account.linkageType"  @change="selLinkageType(account.linkageType)">
                            <a-radio v-for="status in linkageTypeList" :key="status.id" :value="status.id">{{status.name}}</a-radio>
                        </a-radio-group>
                    </a-form-model-item>
                    <a-form-model-item :label="`${account.linkageType == 1 ? '授权' : '发起'}方账户名称`" prop="linkageAccountName" v-if="account.linkageType != 0">
                        <a-input v-model="account.linkageAccountName" placeholder="请输入账户名称" />
                    </a-form-model-item>
                    <a-form-model-item :label="`${account.linkageType == 1 ? '授权' : '发起'}方银行账号`" prop="linkageBankAccount" v-if="account.linkageType != 0">
                        <div class="flex">
                            <a-input v-model="account.linkageBankAccount" placeholder="请输入银行账号" />
                            <a-button style="margin-left: 20px" type='primary' @click="addLinkageBankAccount">添加</a-button>
                        </div>
                    </a-form-model-item>
                </a-form-model>
                <a-divider v-if="account.linkageType == 2 && linkageBankAccount.length > 0" />
                <a-descriptions title="添加记录" v-if="account.linkageType == 2 && linkageBankAccount.length > 0">
                    <a-descriptions-item v-for="(account,i) in linkageBankAccount" :key="account.linkageBankAccount" :label="account.accountName" :span="3">
                        <div class="flex spaceBetween alignCenter">
                            <div>({{account.bankAccount}})</div>
                            <a-button type='link' style="margin-left: 30px" @click="del(i)">删除</a-button>
                        </div>
                    </a-descriptions-item>
                </a-descriptions>
            </div>
        </a-modal>

        <!-- 充值设置 -->
        <a-modal 
            v-model="investVisible" 
            title="充值描述"
            @ok="investVisible = false" 
            @cancel="investVisible = false">
            <div>
                <div>{{investRemark}}</div>
            </div>
        </a-modal>

        <!-- 提现 -->
        <a-modal 
            v-model="withdrawVisible" 
            title="提现申请"
            @ok="withdrawHandleOk" 
            width="50%"
            @cancel="withdrawVisible = false">
            <div>
                <!-- <div>当前账户余额：<span style="color: red">{{accountAmount}}</span> 元</div> -->
                <a-form-model :model="withdrawInfo" ref="withdrawInfoRuleForm" :rules="(hasPayPassword && needPayPassword) ? withdrawInfoRules1 : withdrawInfoRules" :label-col="{ span: 7 }" :wrapper-col="{ span: 17 }">
                    <a-form-model-item label="当前账户余额">
                        <div><span style="color: red">{{accountAmount}}</span> 元</div>
                    </a-form-model-item>
                    <a-form-model-item label="提现金额（元）" prop="amount">
                        <a-input v-model="withdrawInfo.amount" placeholder="请输入提现金额" />
                    </a-form-model-item>
                    <a-form-model-item label="交易密码" prop="payPassword" v-if="hasPayPassword && needPayPassword">
                        <a-input v-model="withdrawInfo.payPassword" placeholder="请输入交易密码" />
                    </a-form-model-item>
                    <a-form-model-item label="备注">
                        <a-input v-model="withdrawInfo.remark" placeholder="最多20字，此备注信息将传给银行" />
                    </a-form-model-item>
                </a-form-model>
                <a-divider/>
                <a-descriptions title="开户银行信息" >
                    <a-descriptions-item label="开户行" >{{withdrawAccount.withdrawalChannel}}</a-descriptions-item>
                    <a-descriptions-item label="账户名称" :span="2">{{withdrawAccount.withdrawalAccountName}}</a-descriptions-item>
                    <a-descriptions-item label="银行账户" >{{withdrawAccount.withdrawalBankAccount}}</a-descriptions-item>
                    <a-descriptions-item label="开户支行" :span="2">{{withdrawAccount.withdrawalSubChannel}}</a-descriptions-item>
                </a-descriptions>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { columns } from './table';
import { getAccountList , createLaborAccount , updateLaborAccount , getLaborAccountDetail , getAccountBalance , getLaborWithdrawConfig , accountWithdraw , getAccountRechargeInfo , getHasPayPassword } from '@/api/services/account';
import { Ellipsis } from '@/components'
export default {
    components: {
        Ellipsis,
    },
    data () {
        return {
            dataList: [],
            page: 1,
            size: 10,
            total: 0,
            startTime: '',
            endTime: '',
            channel: '', // 开户行
            accountName: '', // 账户名称
            bankAccount: '', // 银行账号
            isload: false,
            columns,
            visible: false,
            isAdd: true,
            linkageType: undefined, // 联动设置
            linkageTypeList: [
                { id: 0, name: '未开通'},
                { id: 1, name: '发起方'},
                { id: 2, name: '授权方'},
            ],
            accountTypeList: [
                { id: 1, name: '一般账户'},
                { id: 2, name: '基本账户'},
                { id: 3, name: '临时账户'},
                { id: 4, name: '专业账户'},
            ],
            // 账户详情
            account: {
                id: '',
                bankAccount: '',
                channel: '',
                accountType: undefined,
                linkageType: 0,
                accountName: '',
                accountShortName: '',
                linkageAccountName: '',
                linkageBankAccount: '',
            },
            rules: {
                channel: [
                    { required: true, message: '请输入开户行信息', trigger: 'blur' },
                ],
                bankAccount: [{ required: true, message: '请输入银行账户', trigger: 'blur' }],
                accountName: [{ required: true, message: '请输入账户名称', trigger: 'blur' }],
                accountType: [
                    { required: true, message: '请选择账户类型', trigger: 'blur' },
                ],
                linkageType: [
                    { required: true, message: '请选择联动设置', trigger: 'blur' },
                ],
                linkageAccountName: [],
                linkageBankAccount: [],
            },
            linkageBankAccount: [],
            withdrawVisible: false,
            withdrawAccount: {
                accountId: '',
                withdrawalAccountName: '', // 账户名称
                withdrawalBankAccount: '', // 银行账户
                withdrawalChannel: '', // 开户行
                withdrawalSubChannel: '', // 开户支行
            },
            accountAmount: 0, // 账户余额
            withdrawInfo: {
                accountId: '', // 账户ID
                amount: '', // 提现金额
                remark: '', // 备注信息
                payPassword: '', // 交易密码
            },
            withdrawInfoRules: {
                amount: [{ required: true, message: '请输入提现金额', trigger: 'blur' }],
            },
            withdrawInfoRules1: {
                amount: [{ required: true, message: '请输入提现金额', trigger: 'blur' }],
                payPassword: [{ required: true, message: '请输入交易密码', trigger: 'blur' }],
            },
            investRemark: '', // 充值描述
            investVisible: false,
            hasPayPassword: false,
            needPayPassword: false,
        };
    },
    created(){
        this.getData();
    },
    methods: {
        // 日期筛选
        onDateChange(date,dateStr){
            console.log(date,dateStr)
            if(date.length > 0){
                this.startTime = `${dateStr[0]}`
                this.endTime = `${dateStr[1]}`
            }else{
                this.startTime = ''
                this.endTime = ''
            }
            this.getData()
        },
        // 获取账户列表数据
        getData(){
            let _this = this
            _this.isload = true;
            const params = {
                'pageSize': _this.size,
                'pageIndex': _this.page,
                'endTime': _this.endTime,
                'startTime': _this.startTime,
                'channel': _this.channel,
                'accountName': _this.accountName,
                'bankAccount': _this.bankAccount,
                'linkageType': _this.linkageType,
            }
            getAccountList(params)
            .then(res=>{
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data;
                    _this.total = res.totalCount;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 添加账户
        add(){
            this.isAdd = true;
            this.$refs.ruleForm.resetFields();
            this.account.id = ''
            this.visible = true;
        },
        // 修改账户
        update(item){
            let _this = this
            getLaborAccountDetail(item.id)
            .then(res=>{
                if(res.success){
                    // this.account = res.data
                    _this.account.bankAccount = res.data.bankAccount
                    _this.account.channel = res.data.channel
                    _this.account.id = res.data.id
                    _this.account.accountType = res.data.accountType
                    _this.account.linkageType = res.data.linkageType
                    _this.account.accountName = res.data.accountName
                    _this.account.accountShortName = res.data.accountShortName
                    _this.selLinkageType(_this.account.linkageType)
                    // console.log(res.data.linkageAccounts.length,'res.data.linkageAccounts.length')
                    if(res.data.linkageAccounts != null){
                        if((_this.account.linkageType == 1 || _this.account.linkageType == 2) && res.data.linkageAccounts.length == 1){
                            console.log('走了这里')
                            _this.account.linkageAccountName = res.data.linkageAccounts[0].accountName
                            _this.account.linkageBankAccount = res.data.linkageAccounts[0].bankAccount
                        }else if(this.account.linkageType == 2 && res.data.linkageAccounts.length > 1){
                            _this.linkageBankAccount = res.data.linkageAccounts
                        }
                    }
                    console.log(this.account,'linkageAccounts')
                    _this.isAdd = false;
                    _this.visible = true;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
            
        },
        // 确认添加、修改账户
        handleOk(){
            let _this = this
            if(_this.account.linkageType == 2){
                console.log(_this.account)
                if(_this.account.bankAccount != '' && _this.account.channel != '' && _this.account.accountName != '' && _this.account.accountType != undefined && _this.linkageBankAccount.length > 0){
                    console.log('1112233')
                    _this.$refs.ruleForm.clearValidate()
                    _this.rules.linkageAccountName = []
                    _this.rules.linkageBankAccount = []
                }else{
                    _this.selLinkageType(2)
                }
            }
            _this.$refs.ruleForm.validate(valid => {
                if(valid){
                    var params = {
                        'id': _this.account.id,
                        'bankAccount': _this.account.bankAccount,
                        'channel': _this.account.channel,
                        'accountType': _this.account.accountType,
                        'linkageType': _this.account.linkageType,
                        'accountName': _this.account.accountName,
                        'accountShortName': _this.account.accountShortName,
                    }
                    if(_this.account.linkageType == 1){
                        params.linkageAccounts = [{
                            accountName: _this.account.linkageAccountName,
                            bankAccount: _this.account.linkageBankAccount,
                        }]
                    }else if(_this.account.linkageType == 2){
                        params.linkageAccounts = _this.account.linkageAccountName != '' && _this.account.linkageAccountName != null ? [{
                            accountName: _this.account.linkageAccountName,
                            bankAccount: _this.account.linkageBankAccount,
                        },..._this.linkageBankAccount] : _this.linkageBankAccount
                    }else{
                        params.linkageAccounts = []
                    }
                    var apiUrl = _this.isAdd ? createLaborAccount(params) : updateLaborAccount(params)
                    apiUrl.then(res=>{
                        if(res.success){
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: _this.isAdd ? '添加成功' : '修改成功',
                                duration: 8
                            })
                            _this.visible = false;
                            _this.getData()
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }else{
                    console.log('111')
                }
            })
        },
        // 选择联动设置
        selLinkageType(linkageType){
            console.log(linkageType,'linkageType')
            if(linkageType == 1){
                this.rules.linkageAccountName = [{ required: true, message: '请输入授权方账户名称', trigger: 'blur' }]
                this.rules.linkageBankAccount = [{ required: true, message: '请输入授权方银行账户', trigger: 'blur' }]
            }else if(linkageType == 2){
                this.rules.linkageAccountName = [{ required: true, message: '请输入发起方账户名称', trigger: 'blur' }]
                this.rules.linkageBankAccount = [{ required: true, message: '请输入发起方银行账户', trigger: 'blur' }]
            }else{
                this.rules.linkageAccountName = []
                this.rules.linkageBankAccount = []
            }
        },
        // 添加临时联动账号
        addLinkageBankAccount(){
            console.log(this.account,'this.account')
            if(this.account.linkageBankAccount == ''){
                this.$message.warning(`请输入${this.account.linkageType == '2' ?'发起方' : '授权方'}银行账号`)
                return;
            }
            var acc = this.linkageBankAccount.find(item => item.bankAccount == this.account.linkageBankAccount)
            console.log(acc,'acc')
            if(acc != null){
                this.$notification['error']({
                    message: '温馨提示',
                    description: '当前发起方账户已存在！',
                    duration: 8
                })
            }else{
                this.linkageBankAccount.push({
                    accountName: this.account.linkageAccountName,
                    bankAccount: this.account.linkageBankAccount,
                })
                this.account.linkageAccountName = ''
                this.account.linkageBankAccount = ''
            }
        },
        // 删除临时添加的联动账号
        del(index){
            this.linkageBankAccount.splice(index,1)
        },
        // 跳转详情
        detail(item){
            this.$router.push({ path: '/servicesAccount/accountDetail', query: { 'accountId': item.id }})
        },
        // 提现
        withdraw(item){
            let _this = this;
            _this.getHasPaypassword(item.id);
            if(item.needDealPassword == '1'){
                _this.needPayPassword = true;
            }else{
                _this.needPayPassword = false;
            }
            getLaborWithdrawConfig(item.id)
            .then(async res => {
                if(res.success){
                    if(res.data.accountId){
                        try {
                            _this.withdrawAccount = JSON.parse(JSON.stringify(res.data))
                            _this.withdrawInfo.accountId = item.id;
                            _this.accountAmount = await _this.getAccountBalances(item.id)
                            _this.withdrawVisible = true;
                        } catch (error) {
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: error,
                                duration: 8
                            })
                        }
                    }else{
                        _this.$confirm({
                            title: '温馨提示',
                            content: '当前账户暂未设置提现账户，是否前往设置？',
                            onOk(){
                                _this.$router.push({ path: '/servicesAccount/accountDetail', query: { 'accountId': item.id }})
                            }
                        })
                    }
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 确认提现
        async withdrawHandleOk(){
            let _this = this;
            _this.$refs.withdrawInfoRuleForm.validate( valid => {
                if(valid){
                    if(parseInt(_this.withdrawInfo.amount) > parseInt(_this.accountAmount)){
                        _this.$message.warning('提现金额不能大于账户余额！');
                        reutrn;
                    }
                    accountWithdraw(_this.withdrawInfo)
                    .then(res => {
                        if(res.success){
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: '操作成功',
                                duration: 8
                            })
                            _this.withdrawVisible = false;
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },
        // 获取账户余额信息
        getAccountBalances(id){
            let _this = this;
            return new Promise((resolve,reject) => {
                getAccountBalance(id)
                .then( res => {
                    if(res.success){
                        resolve(res.data)
                    }else{
                        reject(res.errMessage)
                    }
                })
                .catch(err => {
                    reject(err)
                })
            })
        },
        // 查看充值描述
        invest(item){
            let _this = this;
            getAccountRechargeInfo(item.id)
            .then( res => {
                if(res.success){
                    if(res.data){
                        _this.investRemark = res.data;
                        _this.investVisible = true;
                    }else{
                        _this.$notification['error']({
                            message: '温馨提示',
                            description: '暂无充值描述信息',
                            duration: 8
                        })
                    }
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 获取是否设置过交易密码
        getHasPaypassword(accountId){
            let _this = this
            getHasPayPassword(accountId)
            .then(res=>{
                if(res.success){
                    _this.hasPayPassword = res.data;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
    }
}

</script>
<style scoped>

</style>